package com.quan.system.web.controller;

import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quan.common.bean.PageBean;
import com.quan.common.bean.ResultBean;
import com.quan.common.core.MyBaseController;
import com.quan.system.common.dto.SystemUserDTO;
import com.quan.system.entity.SystemUser;
import com.quan.system.entity.SystemUserRole;
import com.quan.system.service.SystemUserRoleService;
import com.quan.system.service.SystemUserService;

/**
 * <p>
 * 通用用户权限系统-用户表 前端控制器
 * </p>
 *
 * @author 杨浩泉
 * @since 2019-06-03
 */
@RestController
@RequestMapping("/system/user")
public class SystemUserController extends MyBaseController {
	
	@Autowired
	private SystemUserService service;

	@Autowired
	private SystemUserRoleService systemUserRoleService;

	/**
	 * 添加
	 * 
	 * @param entity
	 * @param bindingResult
	 * @return
	 */
	@PostMapping("/add")
	public Object add(@Valid @RequestBody SystemUser entity, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultBean.warning(bindingResult.getFieldError().getRejectedValue().toString());
		}
		
		if(this.service.hasExist("username", entity.getUsername(), SystemUser.class)) {
			return ResultBean.warning("该值已存在");
		}

		boolean save = this.service.save(entity);
		if (save) {
			return ResultBean.ok("提交成功");
		} else {
			return ResultBean.failure("提交失败");
		}
	}

	/**
	 * 根据ID删除
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("/deleteById/{id}")
	public Object deleteById(@PathVariable String id) {
		if (StringUtils.isNotBlank(id)) {
			boolean remove = this.service.removeById(id);
			if (remove) {
				return ResultBean.ok();
			} else {
				return ResultBean.failure("通过ID删除失败：[ " + id + " ]");
			}
		}
		return ResultBean.failure("请选项需要删除的记录");
	}

	/**
	 * 批量删除
	 * 
	 * @param params idList:["1","2"]
	 * @return
	 */
	@PostMapping("/deleteBatchIds")
	public Object deleteBatchIds(@RequestBody Map<String, Object> params) {
		if (null != params && !params.isEmpty()) {
			List<Long> idList = JSON.parseArray(params.get("idList").toString(), Long.class);
			boolean remove = this.service.removeByIds(idList);
			if (remove) {
				return ResultBean.ok();
			} else {
				return ResultBean.failure("通过ID删除失败：[ " + idList + " ]");
			}
		}
		return ResultBean.failure("请选项需要删除的记录");
	}

	/**
	 * 修改
	 * 
	 * @param entity
	 * @param bindingResult
	 * @return
	 */
	@PostMapping("/update")
	public Object update(@Valid @RequestBody SystemUser entity, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultBean.failure(bindingResult.getFieldError().getDefaultMessage().toString());
		}
		boolean update = this.service.updateById(entity);
		if (update) {
			return ResultBean.ok("修改成功");
		} else {
			return ResultBean.failure("修改失败");
		}
	}

	/**
	 * 根据ID查询
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("/get/{id}")
	public Object get(@PathVariable Long id) {
		SystemUser entity = this.service.getById(id);
		if (null != entity) {
			return ResultBean.ok(entity);
		} else {
			return ResultBean.failure("通过ID查询失败：[ " + id + " ]");
		}
	}

	/**
	 * 查询所有数据，不分页
	 * 
	 * @param entity
	 * @return
	 */
	@GetMapping(value = "/list")
	public Object list(SystemUser entity) {
		return ResultBean.ok(this.service.list(new QueryWrapper<SystemUser>(entity)));
	}

	/**
	 * 分页查询数据
	 * 
	 * @param entity
	 * @return
	 */
	@GetMapping(value = "/page")
	public Object page(SystemUser entity) {
		return ResultBean.ok(this.service.selectPage(new QueryWrapper<SystemUser>(entity).orderByDesc("ctime"), new PageBean(request)));
	}
	
	/**
	 * 根据用户ID加载用户对应的角色
	 * @param userId
	 * @return
	 */
	@GetMapping(value = "/getRolesByUserId/{userId}")
	public Object getRolesByUserId(@PathVariable String userId) {
		QueryWrapper<SystemUserRole> queryWrapper = new QueryWrapper<SystemUserRole>();
		queryWrapper.eq("user_id", userId);
		return ResultBean.ok(this.systemUserRoleService.list(queryWrapper));
	}
	
	
	/**
	 * 添加、修改、删除用户与角色关联
	 * @param map {"userId": 1, "roles": [1, 2]}
	 * @return
	 */
    @PostMapping("/setUserRole")
    public Object setUserRole(@RequestBody Map<String, Object> map) {
    	
    	String userId = map.get("userId").toString() ;
    	JSONArray parseArray = JSON.parseArray(map.get("roles").toString()) ;
    	
    	if(null != userId) {
    		QueryWrapper<SystemUserRole> queryWrapperDeleteByUserId = new QueryWrapper<SystemUserRole>();
    		queryWrapperDeleteByUserId.eq("user_id", userId);
    		this.systemUserRoleService.remove(queryWrapperDeleteByUserId);
    		
        	if(!parseArray.isEmpty()) {
        		for(int i=0; i<parseArray.size(); i++) {
        			
					  SystemUserRole entity = new SystemUserRole() ;
					  entity.setUserId(Long.parseLong(userId));
					  entity.setRoleId(parseArray.getInteger(i));
					  
					  this.systemUserRoleService.save(entity);
        		}
        	}
    	}
    	
		return ResultBean.ok();
    }
    
    /**
	 * 重置用户登陆密码为[123456]
	 * 
	 * @param params idList:["1","2"]
	 * @return
	 */
	@PostMapping("/batchResetPassword")
	public Object batchResetPassword(@RequestBody Map<String, Object> params) {
		if (null != params && !params.isEmpty()) {
			List<Long> idList = JSON.parseArray(params.get("idList").toString(), Long.class);
			boolean flag = this.service.batchResetPassword(idList);
			if (flag) {
				return ResultBean.ok();
			} else {
				return ResultBean.failure("重置用户登陆密码失败：[ " + idList + " ]");
			}
		}
		return ResultBean.failure("请选项需要重置用户登陆密码的记录");
	}
    
    
    /**
	 * 修改个人登录密码
	 * 
	 * @param dto
	 * @return
	 */
	@PostMapping(value = "/updateMyPassword")
	public Object updateMyPassword(@RequestBody SystemUserDTO dto) {
		try {
			if (StringUtils.isBlank(dto.getOldPassword())) {
				return ResultBean.warning("原密码不能为空");	
			}
			if (StringUtils.isBlank(dto.getNewPassword())) {
				return ResultBean.warning("新密码不能为空");
			}
			this.service.updatePassword(dto.getId(), dto.getOldPassword(), dto.getNewPassword());
			return ResultBean.ok();
		} catch (RuntimeException e) {
			return ResultBean.failure(e.getMessage());
		}
	}

	/**
	 * 修改个人基本信息
	 * 
	 * @param entity
	 * @return
	 */
	@PostMapping(value = "/updateMyInfo")
	public Object updateMyInfo(@RequestBody SystemUser entity) {
		if (StringUtils.isBlank(entity.getRealname())) {
			return ResultBean.warning("姓名不能为空");
		}
		if (StringUtils.isBlank(entity.getEmail())) {
			return ResultBean.warning("邮件地址不能为空");
		}
		if (StringUtils.isBlank(entity.getMobile())) {
			return ResultBean.warning("手机号码不能为空");
		}

//		SystemUser oldUser = this.service.getById(entity.getId()) ;
//		if (null != oldUser.getRealname() && !oldUser.getRealname().equals(entity.getRealname())) {
//			if (this.service.existValue(SystemUser.class, "realName", entity.getRealname()) > 0) {
//				return ResultBean.failure("名称已存在");
//			}
//		}
//		if (null != oldUser.getEmail() && !oldUser.getEmail().equals(entity.getEmail())) {
//			if (this.service.existValue(SystemUser.class, "email", entity.getEmail()) > 0) {
//				return ResultBean.failure("编码已存在");
//			}
//		}
//		if (null != oldUser.getMobile() && !oldUser.getMobile().equals(entity.getMobile())) {
//			if (this.service.existValue(SystemUser.class, "mobile", entity.getMobile()) > 0) {
//				return ResultBean.failure("编码已存在");
//			}
//		}
		entity.setPassword(null);
		entity.setSalt(null);
		this.service.updateById(entity) ;

		return ResultBean.ok();
	}

}
